package cn.drenal.capcap.controller.forum;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import cn.drenal.capcap.common.Response;
import cn.drenal.capcap.entity.*;
import cn.drenal.capcap.entity.dto.ArtworkSubmitDTO;
import cn.drenal.capcap.entity.vo.ArtworkListVO;
import cn.drenal.capcap.entity.vo.forum.ForumArtworkCardVO;
import cn.drenal.capcap.entity.vo.forum.ForumArtworkDetailVO;
import cn.drenal.capcap.mapper.*;
import cn.drenal.capcap.service.ArtworkService;
import cn.drenal.capcap.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 论坛作品控制器
 * 处理论坛端作品的投稿、查询等功能
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/forum/artwork")
public class ForumArtworkController {

    private final ArtworkMapper artworkMapper;

    private final ArtworkService artworkService;

    private final ArtworkFavoriteMapper artworkFavoriteMapper;
    
    private final UserService userService;
    
    private final TagMapper tagMapper;
    
    private final ArtworkTagMapper artworkTagMapper;
    private final ArtworkImageMapper artworkImageMapper;

    /**
     * 删除作品
     *
     * @param id 作品ID
     * @return 删除结果
     */
    @DeleteMapping("/delete/{id}")
    public Response<Void> deleteArtwork(@PathVariable Long id) {
        artworkService.deleteArtwork(id);
        return Response.success();
    }

    /**
     * 投稿作品
     *
     * @param artworkSubmitDTO 作品投稿信息
     * @return 投稿结果
     */
    @PostMapping("/submit")
    public Response<Artwork> submitArtwork(@RequestBody ArtworkSubmitDTO artworkSubmitDTO) {
        // 参数校验
        if (artworkSubmitDTO == null || artworkSubmitDTO.getTitle() == null) {
            return Response.error("参数不完整");
        }
        
        // 获取当前登录用户ID
        Long userId = StpUtil.getLoginIdAsLong();
        
        // 处理自定义标签
        if (artworkSubmitDTO.getTags() != null && !artworkSubmitDTO.getTags().isEmpty()) {
            processCustomTags(artworkSubmitDTO);
        }
        
        // 调用服务层提交作品
        return Response.success(artworkService.submitArtwork(artworkSubmitDTO, userId));
    }
    
    /**
     * 处理自定义标签
     * 如果标签已存在，则使用已有标签ID；如果不存在，则创建新标签
     *
     * @param artworkSubmitDTO 作品提交DTO
     */
    private void processCustomTags(ArtworkSubmitDTO artworkSubmitDTO) {
        List<String> tagNames = artworkSubmitDTO.getTags();
        List<String> tagIds = new ArrayList<>();
        
        for (String tagName : tagNames) {
            // 查询标签是否已存在
            LambdaQueryWrapper<Tag> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Tag::getName, tagName);
            Tag existingTag = tagMapper.selectOne(queryWrapper);
            
            if (existingTag != null) {
                // 标签已存在，使用已有标签ID
                tagIds.add(existingTag.getId().toString());
            } else {
                // 标签不存在，创建新标签
                Tag newTag = new Tag();
                newTag.setName(tagName);
                newTag.setStatus(1); // 设置为启用状态
                tagMapper.insert(newTag);
                
                // 使用新创建的标签ID
                tagIds.add(newTag.getId().toString());
            }
        }
        
        // 更新DTO中的标签列表为标签ID列表
        artworkSubmitDTO.setTags(tagIds);
    }

    /**
     * 按分类获取作品列表（分页）
     *
     * @param categoryId 分类ID
     * @param current 当前页
     * @param size 每页大小
     * @return 作品列表
     */
    @SaIgnore
    @GetMapping("/category/{categoryId}/page")
    public Response<Page<Artwork>> getArtworksByCategoryId(
            @PathVariable String categoryId,
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size) {
        
        Page<Artwork> page = new Page<>(current, size);
        LambdaQueryWrapper<Artwork> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Artwork::getCategoryId, categoryId)
                .eq(Artwork::getStatus, 2) // 只查询已发布的作品
                .orderByDesc(Artwork::getCreateTime);
        
        Page<Artwork> artworkPage = artworkMapper.selectPage(page, queryWrapper);
        return Response.success(artworkPage);
    }

    /**
     * 分页查询作品列表
     *
     * @param current 当前页
     * @param size 每页大小
     * @param title 标题（可选）
     * @param categoryId 分类ID（可选）
     * @param activityId 活动ID（可选）
     * @param tagId 标签ID（可选）
     * @return 作品分页列表
     */
    @SaIgnore
    @GetMapping("/page")
    public Response<Page<ArtworkListVO>> getArtworkPage(
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) Long categoryId,
            @RequestParam(required = false) Long activityId,
            @RequestParam(required = false) Long tagId) {
        // 只查询已发布状态的作品
        Integer status = 2; // 2-已发布
        Page<ArtworkListVO> page = new Page<>(current, size);
        
        // 如果提供了tagId，使用支持标签筛选的方法
        if (tagId != null) {
            return Response.success(artworkService.getArtworkPage(page, categoryId, tagId));
        }
        
        // 否则使用原有方法
        return Response.success(artworkService.getArtworkPage(page, title, status, categoryId, activityId));
    }

    /**
     * 根据分类ID查询作品列表
     *
     * @param categoryId 分类ID
     * @param current 当前页
     * @param size 每页大小
     * @return 作品分页列表
     */
    @SaIgnore
    @GetMapping("/category/{categoryId}")
    public Response<Page<ArtworkListVO>> getArtworksByCategory(
            @PathVariable Long categoryId,
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size,
            @RequestParam(required = false) Long tagId) {
        // 只查询已发布状态的作品
        Integer status = 2; // 2-已发布
        Page<ArtworkListVO> page = new Page<>(current, size);
        return Response.success(artworkService.getArtworkPage(page, categoryId, tagId));
    }

    /**
     * 获取最新作品列表
     *
     * @param current 当前页
     * @param size 每页大小
     * @return 最新作品分页列表
     */
    @SaIgnore
    @GetMapping("/latest-artworks")
    public Response<Page<ForumArtworkCardVO>> getLatestArtworks(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "5") Integer size) {
        Page<Artwork> page = new Page<>(current, size);
        return Response.success(artworkService.getLatestArtworks(page));
    }

    /**
     * 获取萌新求助列表
     * 通过标签关联查询具有萌新求助标签的作品
     *
     * @param current 当前页
     * @param size 每页大小
     * @return 萌新求助分页列表
     */
    @SaIgnore
    @GetMapping("/help-artworks")
    public Response<Page<Artwork>> getHelpArtworks(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "5") Integer size) {
        Page<Artwork> page = new Page<>(current, size);
        return Response.success(artworkService.getHelpArtworks(page));
    }
    
    /**
     * 获取作品详情
     * 实现作品、用户和评论的联合查询，并增加浏览量
     *
     * @param id 作品ID
     * @return 作品详情
     */
    @SaIgnore
    @GetMapping("/detail/{id}")
    public Response<ForumArtworkDetailVO> getArtworkDetail(@PathVariable Long id) {
        // 获取当前登录用户ID，未登录则为null
        Long userId = null;
        try {
            if (StpUtil.isLogin()) {
                userId = StpUtil.getLoginIdAsLong();
            }
        } catch (Exception e) {
            // 未登录，不处理异常
        }
        
        // 增加浏览量
        artworkService.incrementViewCount(id);
        
        // 获取作品详情
        return Response.success(artworkService.getForumArtworkDetail(id, userId));
    }
    
    /**
     * 点赞/取消点赞作品
     *
     * @param id 作品ID
     * @return 操作结果
     */
    @PostMapping("/like/{id}")
    public Response<Boolean> likeArtwork(@PathVariable Long id) {
        // 获取当前登录用户ID
        Long userId = StpUtil.getLoginIdAsLong();
        return Response.success(artworkService.toggleArtworkLike(id, userId));
    }
    
    /**
     * 收藏/取消收藏作品
     *
     * @param id 作品ID
     * @return 操作结果
     */
    @PostMapping("/favorite/{id}")
    public Response<Boolean> favoriteArtwork(@PathVariable Long id) {
        // 获取当前登录用户ID
        Long userId = StpUtil.getLoginIdAsLong();
        
        // 检查作品是否存在
        Artwork artwork = artworkMapper.selectById(id);
        if (artwork == null) {
            return Response.error("作品不存在");
        }
        
        // 检查是否已收藏
        LambdaQueryWrapper<ArtworkFavorite> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ArtworkFavorite::getUserId, userId.toString())
                .eq(ArtworkFavorite::getArtworkId, id.toString());
        ArtworkFavorite existingArtworkFavorite = artworkFavoriteMapper.selectOne(queryWrapper);
        
        boolean isFavorite;
        if (existingArtworkFavorite == null) {
            // 未收藏，添加收藏
            ArtworkFavorite artworkFavorite = new ArtworkFavorite();
            artworkFavorite.setUserId(userId);
            artworkFavorite.setArtworkId(id);
            artworkFavoriteMapper.insert(artworkFavorite);
            isFavorite = true;
        } else {
            // 已收藏，取消收藏
            artworkFavoriteMapper.delete(queryWrapper);
            isFavorite = false;
        }
        
        return Response.success(isFavorite);
    }
    
    /**
     * 检查是否已收藏作品
     *
     * @param id 作品ID
     * @return 是否已收藏
     */
    @GetMapping("/is-favorite/{id}")
    public Response<Boolean> isFavorite(@PathVariable Long id) {
        // 获取当前登录用户ID
        Long userId = StpUtil.getLoginIdAsLong();
        
        // 检查是否已收藏
        LambdaQueryWrapper<ArtworkFavorite> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ArtworkFavorite::getUserId, userId.toString())
                .eq(ArtworkFavorite::getArtworkId, id.toString());
        ArtworkFavorite existingArtworkFavorite = artworkFavoriteMapper.selectOne(queryWrapper);
        
        return Response.success(existingArtworkFavorite != null);
    }
    /**
     * 查看用户的作品
     *
     * @return 用户作品列表
     */
    @GetMapping("/my-works")
    public Response<Page<ForumArtworkCardVO>> getMyWorks(@RequestParam(defaultValue = "1") Integer current,
                                        @RequestParam(defaultValue = "5") Integer size) {
        // 获取当前登录用户ID
        Long userId = StpUtil.getLoginIdAsLong();

        Page<Artwork> artworkPage = artworkService.page(new Page<>(current, size)
                , new LambdaQueryWrapper<Artwork>()
                        .eq(Artwork::getUserId, userId)
                        .orderByDesc(Artwork::getCreateTime)
        );

        Page<ForumArtworkCardVO> voPage = new Page<>();

        BeanUtils.copyProperties(artworkPage, voPage);
        voPage.setRecords(artworkPage.getRecords().stream().map(artwork -> {
            ForumArtworkCardVO vo = new ForumArtworkCardVO();
            BeanUtils.copyProperties(artwork, vo);
            vo.setLikeCount(artworkService.getLikeCount(artwork.getId()));
            return vo;
        }).toList());

        return Response.success(voPage);
    }
    
    /**
     * 获取热门作品列表
     * 按照浏览量排序
     *
     * @param current 当前页
     * @param size 每页大小
     * @return 热门作品分页列表
     */
    @SaIgnore
    @GetMapping("/hot-artworks")
    public Response<Page<ForumArtworkCardVO>> getHotArtworks(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "5") Integer size) {
        // 创建分页对象
        Page<Artwork> page = new Page<>(current, size);
        
        // 构建查询条件：按浏览量降序排序
        LambdaQueryWrapper<Artwork> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Artwork::getStatus, 2) // 只查询已发布的作品
                .orderByDesc(Artwork::getViewCount);
        
        // 执行查询
        Page<Artwork> artworkPage = artworkMapper.selectPage(page, queryWrapper);
        
        // 转换为VO对象
        Page<ForumArtworkCardVO> resultPage = new Page<>();
        BeanUtils.copyProperties(artworkPage, resultPage, "records");
        
        List<ForumArtworkCardVO> records = artworkPage.getRecords().stream().map(artwork -> {
            ForumArtworkCardVO vo = new ForumArtworkCardVO();
            BeanUtils.copyProperties(artwork, vo);
            
            // 设置作者名称
            User user = userService.getById(artwork.getUserId());
            if (user != null) {
                vo.setUsername(user.getUsername());
            }
            
            return vo;
        }).collect(Collectors.toList());
        
        resultPage.setRecords(records);
        return Response.success(resultPage);
    }
    
    /**
     * 获取推荐作品列表
     * 按照点赞数排序
     *
     * @param current 当前页
     * @param size 每页大小
     * @return 推荐作品分页列表
     */
    @SaIgnore
    @GetMapping("/recommended-artworks")
    public Response<Page<ForumArtworkCardVO>> getRecommendedArtworks(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "5") Integer size) {
        // 创建分页对象
        Page<Artwork> page = new Page<>(current, size);
        
        // 获取作品列表并按点赞数排序
        Page<ForumArtworkCardVO> resultPage = artworkService.getRecommendedArtworks(page);
        
        return Response.success(resultPage);
    }
    
    /**
     * 更新作品信息
     *
     * @param id 作品ID
     * @param artworkSubmitDTO 作品更新信息
     * @return 更新结果
     */
    @PutMapping("/update/{id}")
    public Response<Boolean> updateArtwork(@PathVariable Long id, @RequestBody ArtworkSubmitDTO artworkSubmitDTO) {
        // 参数校验
        if (artworkSubmitDTO == null || artworkSubmitDTO.getTitle() == null) {
            return Response.error("参数不完整");
        }
        
        // 获取当前登录用户ID
        Long userId = StpUtil.getLoginIdAsLong();
        
        // 检查作品是否存在
        Artwork artwork = artworkMapper.selectById(id);
        if (artwork == null) {
            return Response.error("作品不存在");
        }
        
        // 检查是否是作品的作者
        if (!artwork.getUserId().equals(userId)) {
            return Response.error("无权限修改此作品");
        }
        
        // 处理自定义标签
        if (artworkSubmitDTO.getTags() != null && !artworkSubmitDTO.getTags().isEmpty()) {
            processCustomTags(artworkSubmitDTO);
            
            // 删除原有标签关联
            LambdaQueryWrapper<ArtworkTag> tagWrapper = new LambdaQueryWrapper<>();
            tagWrapper.eq(ArtworkTag::getArtworkId, id.toString());
            artworkTagMapper.delete(tagWrapper);
            
            // 添加新的标签关联
            for (String tagId : artworkSubmitDTO.getTags()) {
                ArtworkTag artworkTag = new ArtworkTag();
                artworkTag.setArtworkId(id.toString());
                artworkTag.setTagId(tagId);
                artworkTagMapper.insert(artworkTag);
            }
        }
        
        // 处理图片关联
        if (artworkSubmitDTO.getImages() != null) {
            // 删除原有图片关联
            LambdaQueryWrapper<ArtworkImage> imageWrapper = new LambdaQueryWrapper<>();
            imageWrapper.eq(ArtworkImage::getArtworkId, id.toString());
            artworkImageMapper.delete(imageWrapper);
            
            // 添加新的图片关联
            for (int i = 0; i < artworkSubmitDTO.getImages().size(); i++) {
                ArtworkImage artworkImage = artworkSubmitDTO.getImages().get(i);

                // 如果是第一张图片且未设置封面标志，则设为封面
                if (artworkImage.getIsCover() == null) {
                    artworkImage.setIsCover(i == 0 ? 1 : 0);
                }

                // 保存图片关联
                artworkImageMapper.insert(artworkImage);
            }
        }
        
        // 更新作品信息
        artwork.setTitle(artworkSubmitDTO.getTitle());
        artwork.setDescription(artworkSubmitDTO.getDescription());
        artwork.setCategoryId(artworkSubmitDTO.getCategoryId());
        
        // 保存更新
        int result = artworkMapper.updateById(artwork);
        
        return Response.success(result > 0);
    }
}